package com.junke.question.service.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.junke.question.service.entity.SysUser;
import com.junke.question.service.service.ISysUserService;
import com.junke.question.service.utils.JwtUtil;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * JWT自定义过滤器
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    ISysUserService userService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("Authorization");
        if(!StringUtils.isEmpty(token)){
            String username = jwtUtil.getUsername(token);

            if(StringUtils.isEmpty(username)){
                throw new JwtException("token验证失败");
            }
            SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq("user_name", username));
            List<GrantedAuthority> userAuthority = jwtUtil.getUserAuthority(user.getId());
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username,null,userAuthority);
            JwtAuthUser jwtAuthUser = new JwtAuthUser(user);
            authentication.setDetails(jwtAuthUser);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        chain.doFilter(request, response);
    }
}
